package com.sy.common.controller;

import com.sy.common.bean.ResultBean;
import com.sy.common.exception.ValidateException;
import com.sy.common.utils.ResultStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
public class BaseController {
    protected ResultBean success(String msg) {
        return handler(ResultStatus.SUCCESS, msg, null);
    }

    protected ResultBean success(String msg, Object data) {
        return handler(ResultStatus.SUCCESS, msg, data);
    }

    protected ResultBean fail(String msg) {
        return handler(ResultStatus.FAIL, msg, null);
    }

    protected ResultBean fail(String msg, Object data) {
        return handler(ResultStatus.FAIL, msg, data);
    }

    protected ResultBean gotoResult(int rs,String msg) {
        return rs == 1 ? success(msg+"成功") : fail(msg+"失败");
    }
    protected ResultBean gotoResult(int rs,String msg,Object data) {
        return rs == 1 ? success(msg+"成功",data) : fail(msg+"失败");
    }

    /**
     * 后端校验
     *
     * @param result
     */
    protected void validate(BindingResult result) {
        List<FieldError> list = result.getFieldErrors();
        if (null != list && list.size() > 0) {
            Map error = new HashMap(); //存储作物字段
            list.forEach(o -> {
                error.put(o.getField(), o.getDefaultMessage());
            });
            throw new ValidateException(error);
        }
    }

    ResultBean handler(ResultStatus status, String msg, Object data) {
        return new ResultBean<>(status.getCode(), msg, data);
    }
}
